from flask import Blueprint,request,make_response,jsonify,redirect
import json, random, time, requests,functools
from application.models.users.user import *
from db import db
home_blue = Blueprint("homeblue", __name__)


def getTags():
    sql = "select * from tags"
    res = db.findAll(sql)
    return res

def getctype():
    sql = "select * from ctype"
    res = db.findAll(sql)
    return res


# @home_blue.route("/home")
# def gethome():
#     ctypetlist = getctype()
#     tagslist = getTags()
#     return jsonify({
#         "code": 200,
#         "ctypelist": ctypetlist,
#         "tagslist": tagslist
#     })


@home_blue.route("/getHomeCourse")
def getHomeGourse1():
    # 获取类型
    ctypetlist = getctype()
    # 获取标签
    tagslist = getTags()
    # 获取当前页面
    page = request.args.get("page")
    # 获取查询条件
    tagid = request.args.get("tagid")
    typeid = request.args.get("type")

    where = ""
    if int(typeid) > 0:
        where = where + " and c.ctype=" + typeid

    if int(tagid) > 0:
        tsql = "select count(c.id) as tcount from course as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid="+tagid
        sql = "select * from course as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid="+tagid
    else:
        sql = "select * from course as c  where 1=1"
        tsql = "select count(c.id) as  tcount   from course as c  where 1=1"

    if where:
        sql = sql + " "+where
        tsql = tsql + " "+where

    # 查询总共有多少条
    res = db.findone(tsql)
    total = res['tcount']
    page_size = 2
    start = (int(page)-1)*page_size
    sql = sql + " limit %d,%d" % (start, page_size)
    courselist = db.findAll(sql)
    print(sql)
    return jsonify({"code": 200, "tlist": ctypetlist, 'taglist': tagslist, 'clist': courselist, "total": total, "page_size":  page_size})


@home_blue.route('/detail')
def detail():
    # 获取课程id
    id = request.args.get('id')
    sql = "select c.id,s.id as sid,c.descrip,c.tcount,s.name,s.url,c.ctype from course as c inner join jie as s on c.id=s.courseid where c.id=%d" % (
        int(id))
    res = db.findAll(sql)
    section = []
    for i in res:
        section.append(
            {'id': i['id'], 'name': i['name'], 'url': i['url'], 'courseid': i['id']})
    course = {'id': res[0]['id'], 'ctype': res[0]['ctype'], 'name': res[0]['name'],
              'descrip': res[0]['descrip'], 'tcount': res[0]['tcount']}
    return jsonify({'code': 200, 'clist': course, 'slist': section})



